<template>
  <page-header title="发贴"></page-header>
  <view class="box">
    <view class="tips">
      <image src="../../static/img/tips.png" mode="scaleToFill" class="icon" />
      <view style="font-weight: 600;"> 发表的内容更贴近话题，会更容易通过审核哦 </view>
    </view>
    <view class="post-item" style="margin-top: 20rpx;min-height: 60vh;">
      <view style="font-weight: 600;font-style: italic;">{{ getNowTime() }}</view>
      <view class="section">{{ '# '+postData.sectionName }}</view>
      <textarea auto-height auto-focus class="input" maxlength="1000" placeholder="这一刻的想法..."
        v-model.trim="postData.content" placeholder-style="font-size:28rpx;"></textarea>
      <view class="group">
        <view v-if="tempFilePaths.length" class="upload-chequer img" v-for="(item, index) in tempFilePaths"
          :key="index">
          <image :src="item" mode="aspectFill" />
          <image @tap="handleDelete(index)" class="close" src="../../static/images/payment-close.png"></image>
        </view>
        <view class="upload-chequer" @tap="getUploadImg" v-if="tempFilePaths.length < 9">
          <view class="cross">
            ＋
          </view>
          <view style="font-weight: bold;border-bottom: 1px solid black;">上传照片</view>
        </view>
      </view>
    </view>
    <view class="button" @tap="post">发送</view>
  </view>
</template>

<script setup>
  import {
    onUnload
  } from '@dcloudio/uni-app';
  import {
    ref,
    reactive
  } from 'vue';
  const handleDelete = (index) => {
    Data.tempFilePaths.splice(index, 1)
    Data.tempFiles.splice(index, 1)
    uni.showToast({
      title: '删除成功',
      icon: 'none'
    })
  }
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad((options) => {
    postData.value.sectionId = options.sectionId
    postData.value.sectionName = options.sectionName
  })
  onUnload(() => {
    if (Data.timer != null) {
      clearInterval(Data.timer)
      Data.timer = null
    }
  })
  const Data = reactive({
    imgNum: 9, // 图片上传数量，默认1，最大9
    resourcesUrl: import.meta.env.VITE_APP_RESOURCES_URL,
    resourcesActionType: import.meta.env.VITE_APP_RESOURCES_ACTION_TYPE,
    notImg: false,
    tempFilePaths: [], // 图片上传列表
    tempFiles: [],
    dataForm: {},
    attachFiles: [],
    feilType: [],
    ossList: null,
    timer: null
  })
  const {
    tempFilePaths,
    timer
  } = toRefs(Data)
  const postData = ref({
    content: '',
    sectionId: 0,
    sectionName: '',
    files: []
  })
  const valid = ref(true)
  const post = async () => {
    if (postData.value.content == '') {
      uni.showToast({
        title: "内容不能为空",
        icon: 'none',
        duration: 1000
      })
      return
    }
    valid.value = true
    if (Data.tempFiles) {
      beforeUpload()
    }
    if (valid.value) {
      let len = Data.tempFilePaths.length
      Data.timer = null
      if (len > 0) {
        uni.showLoading({
          title: "上传图片中"
        })
      }
      for (let i = 0; i < Data.tempFilePaths.length; i++) {
        const params = {
          url: '/mall4cloud_biz/oss/upload_minio',
          filePath: Data.tempFilePaths[i],
          name: 'file',
          callBack: res => {
            len--;
            const data = JSON.parse(res).data
            const imgUrl = Data.resourcesUrl + '/' + data.dir + data.fileName
            postData.value.files.push({
              "fileUrl": imgUrl,
              "seq": "0",
              "fileType": "bmp"
            })
          }
        }
        http.upload(params)
      }
      Data.timer = setInterval(() => {
        if (!len || len < -5000) {
          uni.hideLoading()
          http.request({
            url: '/mall4cloud_point/u/post/add',
            method: 'POST',
            data: postData.value
          }).then((res) => {
            uni.showToast({
              title: '发帖成功,待审核通过后展示',
              icon: 'none',
              duration: 500
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 500)
          })
          clearInterval(Data.timer)
          Data.timer = null
        }
      }, 10)

    }

  }
  /**
   * 校验图片合法性
   */
  const beforeUpload = () => {
    for (let i = 0; i < Data.tempFilePaths.length; i++) {
      const isSize = Data.tempFiles[i].size / (1024 * 1024)
      if (isSize > 2) {
        uni.showToast({
          title: `第${i + 1}张图片大小超过2M`,
          icon: 'none'
        })
        valid.value = false
        return
      }
    }
  }
  /**
   * 上传图片
   */
  const getUploadImg = () => {
    uni.chooseImage({
      count: Data.imgNum, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const length = res.tempFilePaths.length <= 9 ? res.tempFilePaths.length : 9
        for (let i = 0; i < length; i++) {
          Data.tempFilePaths.push(res.tempFilePaths[i])
        }
        for (let i = 0; i < length; i++) {
          Data.tempFiles.push(res.tempFiles[i])
        }
      },
      fail: (err) => {
        if (err.errMsg == 'chooseImage:fail cancel') {
          uni.showToast({
            title: '取消上传',
            icon: 'none'
          })
        }
      }
    })
  }
  const getNowTime = () => {
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekDay = weekDays[date.getDay()];
    return `${year}年${month}月${day}日 ${weekDay}`;
  }
</script>

<style>
  page {
    background-color: #FFFAF4;
  }
</style>

<style lang="scss" scoped>
  .box {
    padding: 30rpx;

    .section {
      font-weight: 600;
      margin: 10px 0;
      border: 1px solid;
      border-radius: 30rpx;
      box-sizing: border-box;
      padding: 0 20rpx;
      width: fit-content;
    }

    .tips {
      width: 570rpx;
      margin: 0 auto;
      display: flex;
      align-items: flex-end;

      .icon {
        width: 50rpx;
        height: 50rpx;
        margin-right: 20rpx;
      }
    }

    .input {
      box-sizing: border-box;
      width: 100%;
      margin: 30rpx 0;
    }

    .button {
      color: #5b4523;
      background: #FDE9CE;
      height: 90rpx;
      line-height: 90rpx;
      border-radius: 120rpx;
      text-align: center;
      font-size: 32rpx;
      font-weight: 600;
      margin: 40rpx;
    }

    .group {
      display: flex;
      flex-wrap: wrap;
    }

    .img {
      border: none;
    }

    .upload-chequer {
      width: 200rpx;
      height: 200rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      border: 2rpx dashed #ccc;
      border-radius: 4px;
      margin-left: 10rpx;
      margin-top: 10rpx;
      position: relative;

      .close {
        position: absolute;
        right: 5rpx;
        top: 5rpx;
        width: 25rpx;
        height: 25rpx;
        padding: 5rpx;
        background-color: #ccc;
        border-radius: 50%;
      }

      &:nth-child(3n+1) {
        margin-left: 0rpx;
      }

      .cross {
        font-size: 48px;
        font-weight: 200;
        color: #ccc;
      }
    }
  }

  .bottom {
    background-color: red;
    color: #fff;
    font-weight: bold;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 100rpx;
    text-align: center;
    line-height: 100rpx;
  }
</style>
